#!/usr/bin/env python
# -*- coding: utf-8 -*-
from config import JBOT_PATH
import os


class Notes:

    def __init__(self, query):
        self.notes_file = JBOT_PATH+"/notes.txt"
        self.notes = ["#0 empty"]
        self.last_id = 0
        self.read_notes()
        self.message = None
        if query:
            action, content = self.parse(query)
            self.message = self.process(action, content)
    def __unicode__(self):
        return self.message or None
    def __string__(self):
        return self.__unicode__()

    def parse(self, query):
        try: 
            query = query.decode('utf-8')
            print "encoded to utf-8..."
        except: 
            print "cant encode..."

        if True:#try:
            print u"обрабатываю запрос %s"%query
            query = " " + query + " "

            note_string, search_string = None, None

            if query == 'exit': exit(0)
            if u"запиши заметку" in query or u"добавь заметку" in query or u"запомни заметку" in query:
                note_string = query.split(u"запиши заметку")[1].strip()
            elif u"запиши" in query:
                note_string = query.split(u"запиши")[1].strip()
            elif u"найди заметку про" in query:
                search_string = query.split(u"найди заметку про")[1].strip()
            elif u"найди заметку" in query:
                search_string = query.split(u"найди заметку")[1].strip()

            if note_string: return "save_note", note_string
            if search_string: return "search_note", search_string
            #print note_string, search_string
            return True, None
        else:#except Exception as e:
            print e
            return False, None

    def get_last_id(self): return self.last_id
    def get_next_id(self): return self.get_last_id()+1;

    def read_notes(self):
        if os.path.exists(self.notes_file):
            f = open(self.notes_file, "r")
            raw_notes = f.readlines()
            for line in raw_notes:
                if line and "#" in line and " " in line:
                    self.last_id = int(line.split()[0].strip("#"))
                    self.notes.append(line.strip("\n").decode('utf-8'))
                    #self.notes.append(line)
            f.close()
        else:
            f = open(self.notes_file, "w")
            f.close()
            return False
        return True

    def save_note(self, note_string):
        try:
            f = open(self.notes_file, "a")
            to_write = u"#{0} {1}\n".format(self.get_next_id(), note_string).encode('utf-8')
            f.write(to_write)
            f.close()
            return self.get_next_id()
        except Exception as e:
            print "save_note error: ", e
            return False
    
    def search_notes(self, search_string):
        results = []
        for note in self.notes:
            if search_string in note:
                results.append(note)
        if results == []: return None
        return {'count': len(results), 'results': results, 'last': results[-3:]}

    def process(self, action, content):
        print u"action {0} content {1}".format(action, content)
        if action:
            if action == 'save_note' and content!=None:
                last_id = self.save_note(content)
                if last_id and last_id>0: return u"Заметка сохранена под номером #{0}".format(last_id)
                else: return u"Не удалось сохранить заметку..."
            if action == 'search_note' and content!=None:
                result = self.search_notes(content)
                if result and result['count']>0:
                    return u"Нашел {0}: {1}".format(result['count'], "\n".join(result['last']))
            return u"Не понял что делать..."
        else:
            return False

if __name__ == "__main__":
    print u"Введите команду"
    while True:
        query = ''
        query = raw_input()
        if query == 'exit': exit(0)
        notes = Notes(query)
        print notes.message or u"Ничего..."


    


